/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup 商品
 * @api {GET} api/product/list 商品列表
 * @apiName api/product/list
 * @apiExample {js} axios 例子:
 *  axios.get('http://39.105.38.34:8080/api/product/list', {
 *    params: {
 *      size: 10,
 *      page: 1,
 *    }
 *  });
 * @apiHeader {String} authorization 用户登录或注册成功时返回的 token
 * @apiParam {Number} [page=1] 分页的页数
 * @apiParam {Number} [size=10] 每页的条数
 * @apiSuccess (请求成功) {Array} storelist 商品列表
 * @apiuse  ErrorResponse
 */

const { query } = require('../../helper/db');
const { door, ok } = require('../../helper/util');


module.exports = async ctx => {
  var token = ctx.headers.authorization;
  await door(token);
  var params = ctx.query;
  var sql = ['select * from product where 1 = 1'];
  var values = [];
  var size = params.size ? params.size : 10;
  var page = params.page ? params.page : 1;
  var end = size * page;

  sql.push('order by id desc limit ?, ?');

  values.push(end - 10);
  values.push(end);

  var storelist = await query(sql.join(' '), values);
  if (!storelist.length) return ctx.body = ok({ storelist: [] });

  var orderIDs = storelist.map(item => item.id);
  var imagesList = await query('select * from productImg where productid in (?)', [orderIDs]);
  var detailList = await query('select * from productDetail where productid in (?)', [orderIDs]);
  var optionList = await query('select * from productOption where productid in (?)', [orderIDs]);

  var storelist = await query(sql.join(' '), values);
  storelist.forEach(item => {
    item.images = [];
    item.detail = [];
    item.options = [];

    imagesList.forEach(images => {
      if (item.id !== images.productid) return;
      item.images.push(images.src);
    })

    detailList.forEach(detail => {
      if (item.id !== detail.productid) return;
      item.detail.push(detail.src);
    })

    optionList.forEach(option => {
      if (item.id !== option.productid) return;
      item.options.push({
        name: option.name,
        price: option.price, // 规格价格
        originPrice: option.originPrice, // 规格原价
        salesVolume: option.salesVolume, // 销量
        productid: option.id,
        createdat: option.createdat,
      });
    })
  })

  ctx.body = ok({ storelist });
}

